package daily;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.commons.lang.math.RandomUtils;

public class CacheDemoTest{

	public static void main(String[] args) {
		final CacheDemTest cacheDemo=new CacheDemTest();
		Executors.newScheduledThreadPool(3).scheduleWithFixedDelay(
				new Runnable(){

					@Override
					public void run() {
						System.out.println(Thread.currentThread().getName()+" "+cacheDemo.getData("1"));
					}
					
				}, 2, 5, TimeUnit.SECONDS);

	}

}

class CacheDemTest{
	private Map<String,Object> cacheData=new HashMap<String,Object>();
	private ReadWriteLock lock=new ReentrantReadWriteLock();
	volatile boolean cacheValid=false;
	
	public Object getData(String key){
		lock.readLock().lock();
		if(!cacheValid){
			try {
				if(!cacheData.containsKey(key)){
					lock.readLock().unlock();
					lock.writeLock().lock();
					try {
						if(!cacheValid){
							String value=RandomUtils.nextInt(100000)+"";
							cacheData.put(key, value);
							cacheValid=true;
						}
					}finally{
						lock.readLock().lock();
						lock.writeLock().unlock();
					}
				}
			}finally{
				lock.readLock().unlock();
			}
		}
		return cacheData.get(key);
	}
}
